﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Configuration;

namespace ET.Monitor.DAL
{
    public class DeviceDAL
    {
        double dlVal = 0;
        object objJudge = null, obj = null;
        string strSql = "", strErrMsg = "";
        DataTable dt = new DataTable();

        InvokeWebService iw = new InvokeWebService();
        string rtdbRelationAddress = "";
        string rtdbRealTimeAddress = "";
        string rtdbNameSpace = "";

        public DeviceDAL()
        {
            rtdbRelationAddress = ConfigurationManager.ConnectionStrings["RelationURL"].ConnectionString;
            rtdbRealTimeAddress = ConfigurationManager.ConnectionStrings["RealTimeURL"].ConnectionString;
            rtdbNameSpace = ConfigurationManager.ConnectionStrings["NameSpace"].ConnectionString;
        }

        #region 大类故障次数
        public DataTable GetFaultRecordCount(string id, DateTime sTime, DateTime eTime)
        {
            strSql = string.Format(@"select COUNT(*) NUM,fu.T_PLANTDESC,fu.T_TYPEDESC,fu.T_WATCHID,fu.T_ORGID from (select fat.T_WATCHID, fat.T_STARTTIME,fat.T_ENDTIME,fat.T_TYPEDESC,ti.T_PLANTDESC,ti.T_ORGID from (select ft.T_WATCHID,ft.T_STARTTIME,ft.T_ENDTIME,ft.T_ORGID T_UNITID ,ft.T_TYPEDESC,u.T_DISTRICTID from (select DISTINCT f.T_WATCHID,f.T_STARTTIME,f.T_ENDTIME,f.T_ORGID,e.T_TYPEDESC from (select  T_WATCHID,T_STARTTIME,T_ENDTIME,T_ORGID From T_INFO_FAULTRECORD where T_ORGID in(select distinct T_UNITID  From T_BASE_UNIT  where  T_MACHINEID='{0}') and  (T_STARTTIME>'{1}' and T_ENDTIME<'{2}' or T_ENDTIME is null or T_ENDTIME between '{3}' and '{4}') and T_Watchid in (select T_TYPEID from T_BASE_FAULTPARA )) f left join T_BASE_FAULTPARA p on f.T_WATCHID=p.T_TYPEID left join T_BASE_FAULTTYPE e on p.T_TYPEID=e.T_TYPEID) ft left join T_BASE_UNIT u on ft.T_ORGID=u.T_UNITID) fat left join T_BASE_DISTRICT d on fat.T_DISTRICTID=d.T_DISTRICTID left join  T_INFO_PLANT ti on d.T_ORGID = ti.T_ORGID) fu group by fu.T_PLANTDESC,fu.T_TYPEDESC,fu.T_WATCHID,fu.T_ORGID", id, sTime, eTime, sTime, eTime);

            //            strSql = @"select fl.NUM, fl.T_TYPEDESC,fl.T_WATCHID,o.T_ORGDESC_CN,o.T_ORGDESC_EN,O.T_ORGID  from (
            //select COUNT(*) NUM, fu.T_DISTRICTID,fu.T_ORGID,fu.T_WATCHID,fu.T_TYPEDESC from (
            //select fat.T_WATCHID,fat.T_STARTTIME,fat.T_ENDTIME,fat.T_UNITID ,fat.T_TYPEDESC,fat.T_DISTRICTID,d.T_ORGID from (
            //select ft.T_WATCHID,ft.T_STARTTIME,ft.T_ENDTIME,ft.T_ORGID T_UNITID ,ft.T_TYPEDESC,u.T_DISTRICTID from (
            //select DISTINCT f.T_WATCHID,f.T_STARTTIME,f.T_ENDTIME,f.T_ORGID,e.T_TYPEDESC from (
            //select  T_WATCHID,T_STARTTIME,T_ENDTIME,T_ORGID From T_INFO_FAULTRECORD where 
            //T_ORGID in(select distinct T_UNITID  From T_BASE_UNIT  where  T_MACHINEID='" + id + "') and ";
            //            strSql += " (T_STARTTIME>'" + sTime + "' and T_ENDTIME<'" + eTime + "' or T_ENDTIME is null or T_ENDTIME between '" + sTime + "' and '" + eTime + "')";
            //            strSql += @" and T_Watchid in (select T_TYPEID from T_BASE_FAULTPARA )) f right join T_BASE_FAULTPARA p on f.T_WATCHID=p.T_TYPEID left join T_BASE_FAULTTYPE
            //e on p.T_TYPEID=e.T_TYPEID) ft left join 
            //T_BASE_UNIT u on ft.T_ORGID=u.T_UNITID) fat left join T_BASE_DISTRICT d on fat.T_DISTRICTID=d.T_DISTRICTID) fu group by fu.T_TYPEDESC,fu.T_FAULTRECORD_CN,
            //fu.T_WATCHID,fu.T_ORGID) fl left join T_BASE_ORG o on fl.T_ORGID=o.T_ORGID";


            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }
        #endregion

        #region 获取设备组织机构树
        public DataTable GetDevice()
        {
            strSql = @"
select mc.T_COMPANYID,mc.T_MACHINEID,mc.T_TYPEID,mc.T_COMPANYDESC_CN,mc.T_COMPANYDESC_EN,e.T_TYPEDESC_CN,e.T_TYPEDESC_EN from (
select c.T_COMPANYID,c.T_COMPANYDESC_CN,c.T_COMPANYDESC_EN,m.T_MACHINEID,m.T_TYPEID from T_BASE_MACHINECOMPANY c inner join T_BASE_MACHINE m 
on c.T_COMPANYID = m.T_COMPANYID) mc inner join T_BASE_EQUIPTYPE e on mc.T_TYPEID = e.T_TYPEID";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }
        #endregion

        #region 故障原因
        public object GetFaultReason(string id)
        {
            strSql = "select T_REASON from  T_INFO_FAULTADVICE where T_FAULTID='" + id + "'";
            return iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 故障建议
        public object GetFaultProposal(string id)
        {
            strSql = "select T_ADVICE from  T_INFO_FAULTADVICE where T_FAULTID='" + id + "'";
            return iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 编辑故障
        public bool EditFault(string id, string resion, string plant)
        {
            strSql = strSql = string.Format(@"select isnull(count(*),0) from T_INFO_FAULTADVICE where T_FAULTID='{0}'", id);
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            if (Convert.ToInt32(obj.ToString()) == 0)
                strSql = string.Format(@"insert into  T_INFO_FAULTADVICE(T_FAULTID,T_REASON,T_ADVICE) values('{0}','{1}','{2}')", id, resion, plant);
            else
                strSql = string.Format(@"update T_INFO_FAULTADVICE set T_REASON='{0}',T_ADVICE='{1}' where T_FAULTID='{2}'", resion, plant, id);
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 获取类型
        IList<Hashtable> list = null;
        public IList<Hashtable> GetFaultName()
        {
            strSql = "select T_TYPEID,T_TYPEDESC from T_BASE_FAULTTYPE";


            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            list = DataTableToList(dt);
            return list;
        }
        #endregion

        #region List 转换
        public IList<Hashtable> DataTableToList(DataTable dt)
        {
            IList<Hashtable> list = null;
            if (dt != null && dt.Rows.Count > 0)
            {
                list = new List<Hashtable>();
                Hashtable ht = null;
                foreach (DataRow row in dt.Rows)
                {
                    ht = new Hashtable();
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (row[col.ColumnName] != null && !string.IsNullOrEmpty(Convert.ToString(row[col.ColumnName])))
                        {
                            ht.Add(col.ColumnName.ToUpper(), row[col.ColumnName]);
                        }
                        else
                        {
                            ht.Add(col.ColumnName.ToUpper(), "");
                        }
                    }
                    list.Add(ht);
                }
            }
            return list;
        }
        #endregion


        #region 获取电站下 其他设备
        public IList<Hashtable> GetDevice(string id)
        {
            //获取设备信息
            strSql = @"select T_UNITID,T_UNITDESC_CN From T_BASE_UNIT where T_UNITID in (select T_UNITID from T_BASE_UNIT left join T_BASE_MACHINE on T_BASE_UNIT.T_MACHINEID=T_BASE_MACHINE.T_MACHINEID
 where T_BASE_UNIT.T_DISTRICTID in (select T_DISTRICTID from T_BASE_DISTRICT where T_ORGID = '" + id + "') and T_BASE_MACHINE.T_TYPEID !='nbq') order by I_ORDER desc";
            DataTable dtDevice = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            string[] deviceID = dtDevice.AsEnumerable().Select(x => x["T_UNITID"].ToString()).ToArray();
            //string[] deviceName = dt.AsEnumerable().Select(x => x["T_UNITDESC_CN"].ToString()).ToArray();

            strSql = "select T_UNITID,T_FIELD,T_DESC_CN,I_ORDER from T_BASE_UNITINFO where T_UNITID in (" + "'" + string.Join("','", deviceID) + "'" + ") and t_type='1' order by I_ORDER asc";

            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            deviceID = dt.AsEnumerable().Select(x => x["T_UNITID"].ToString()).Distinct().ToArray();

            string[] point = new string[deviceID.Length * 3];
            string[] name = new string[deviceID.Length * 3];
            for (int i = 0; i < deviceID.Length; i++)
            {
                string[] dName = dt.AsEnumerable().Where(p => p["T_UNITID"].ToString() == deviceID[i]).OrderBy(p => p.Field<int>("I_ORDER")).Select(x => x["T_DESC_CN"].ToString()).ToArray();
                string[] dPoint = dt.AsEnumerable().Where(p => p["T_UNITID"].ToString() == deviceID[i]).OrderBy(p => p.Field<int>("I_ORDER")).Select(x => x["T_FIELD"].ToString()).ToArray();

                point[i * 3] = dPoint[0];
                point[i * 3 + 1] = dPoint[1];
                point[i * 3 + 2] = dPoint[2];

                name[i * 3] = dName[0];
                name[i * 3 + 1] = dName[1];
                name[i * 3 + 2] = dName[2];
            }

            PointDAL dp = new PointDAL();
            double[] val = (double[])dp.GetRealVals(point);
            IList<Hashtable> list = new List<Hashtable>();
            for (int i = 0; i < deviceID.Length; i++)
            {
                Hashtable ht = new Hashtable();
                ht.Add("deviceId", deviceID[i]);
                var rllist = dtDevice.AsEnumerable().Where(p => p["T_UNITID"].ToString() == deviceID[i]).Select(x => x["T_UNITDESC_CN"].ToString()).ToArray()[0];

                ht.Add("deviceName", rllist);

                ht.Add("attribute", name[i * 3] + "," + name[i * 3 + 1] + "," + name[i * 3 + 2]);
                ht.Add("attributeVal", val[i * 3] + "," + val[i * 3 + 1] + "," + val[i * 3 + 2] );

                list.Add(ht);
            }
            return list;
        }

        #endregion

        #region 其他设备详细信息
        public ArrayList GetDevicePointInfo(string id)
        {
            ArrayList list = new ArrayList();
            strSql = "select T_FIELD,T_DESC_CN,I_ORDER from T_BASE_UNITINFO where T_UNITID='" + id + "' and t_type='0' order by I_ORDER asc";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            if (dt == null || dt.Rows.Count == 0)
                return list;

            string[] name = new string[dt.Rows.Count];
            string[] points = new string[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                name[i] = dt.Rows[i]["T_DESC_CN"].ToString();
                points[i] = dt.Rows[i]["T_FIELD"].ToString();
            }
            PointDAL dp = new PointDAL();
            double[] val = (double[])dp.GetRealVals(points);

            list.Add(name);
            list.Add(points);

            return list;
        }
        #endregion
    }
}
